package cn.zcy.springboot_springsecurity.config;

import cn.zcy.springboot_springsecurity.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

//@Configuration
public class MyWebSpringSecurityConfiguration2 extends WebSecurityConfigurerAdapter {

    @Autowired
    IUsersService usersService;

    /**
     * 不加密
     *
     * @return
     */
/*    @Bean
    public PasswordEncoder passwordEncoder(){

        return NoOpPasswordEncoder.getInstance();
    }*/
    @Bean
    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }

    /**
     * @param auth 认证管理器
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        //指定使用哪个service
        auth.userDetailsService(usersService);
//        auth.inMemoryAuthentication().withUser("zcy2")
//                .password(passwordEncoder().encode("333333"))
//                .authorities("admin");
    }

    /**
     * 自定义登录(授权）
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //认证
        http.formLogin() //表单登录
//        .usernameParameter("name")
//                .passwordParameter("password") //指定登录用户密码参数
                .loginPage("/login.html")
                .loginProcessingUrl("/user/login")
                .defaultSuccessUrl("/success.html");
        //授权
        http.authorizeRequests()
                .antMatchers("/login.html", "/user/login").permitAll() //不需要认证的
                .anyRequest().authenticated();

        http.csrf().disable();// 关闭csrf保护，跨站点伪造攻击
    }
}
